package ase.eleitweg.client.gui;

import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.events.*;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.swtdesigner.SWTResourceManager;

import edu.uci.ics.jung.utils.UnifiedUserData;

import org.eclipse.nebula.widgets.gallery.*;

import ase.eleitweg.LocalModule;
import ase.eleitweg.TestDBMemoryFilled;
import ase.eleitweg.common.*;
import ase.eleitweg.common.fail.InconsistentDataException;
import ase.eleitweg.server.*;
import ase.eleitweg.client.gui.utils.*;
import org.apache.log4j.*;

import java.awt.Desktop;
import java.io.*;
import java.util.*;
import javax.activation.*;

public class HauptmenueClient_gui implements ClientHandle, java.io.Serializable{
	
	private Text beschreibungDerInstanzText;
	private static final long serialVersionUID = 100L;
	private ServerUserHandle suh;
	private RunManager rm;
	
	private User me;
	
	private transient Logger log = Logger.getLogger(this.getClass());

	private Table table_1;
	private Table table;
	protected Shell shell;
	
	private Gallery gallery;
	private GalleryItem acceptedItem;
	private GalleryItem incomingItem;
	private GalleryItem startableItem;
	
	private Button akzeptierenButton = null;
	private Button zuruecklegen = null;
	
	private Run selectedIncomming = null;
	private Run selectedAccepted = null;
	private Workflow selectedStartable = null;
	
	private File selectedFile = null;
	
	private Cursor waitCursor = null;
	private Cursor normCursor = null;
	
	private java.util.List<Document> documents = new ArrayList<Document>();
	
	final protected Display display = Display.getDefault();
	
	private HauptmenueClient_gui() {
		
	}
	
	private boolean isAcceptedSel() {
		if(gallery.getSelectionCount()==1) {
			if(gallery.getSelection()[0].equals(acceptedItem)) {
				return true;
			}
		}
		return false;
	}
	
	private boolean isIncomingSel() {
		if(gallery.getSelectionCount()==1) {
			if(gallery.getSelection()[0].equals(incomingItem)) {
				return true;
			}
		}
		return false;
	}
	
	private boolean isStartableSel() {
		if(gallery.getSelectionCount() == 1) {
			if(gallery.getSelection()[0].equals(startableItem)) {
				return true;
			}
		}
		return false;
	}
	
	private void showError(String reason, Exception e) {
		if(shell != null) {
			Error_gui eg = new Error_gui(shell, 0, reason);
			eg.open();
		} else {
			Error_gui eg = new Error_gui(new Shell(), 0, reason);
			eg.open();
		}
		e.printStackTrace();
		shell.close();
	}
	
	public HauptmenueClient_gui(ServerUserHandle suh, User me) {
		this.suh = suh;
//		try {
//			suh.registerClient(this);
//		} catch (RemoteException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		
		this.me = me;
		try {
			rm = suh.getRunManager();
			rm.registerClient((ClientHandle) UnicastRemoteObject.exportObject(this, 0));
		} catch (RemoteException e) {
			showError("Cannot reach server!", e);
		}
	}

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws RemoteException {
		Injector injector = Guice.createInjector(new TestDBMemoryFilled(), new LocalModule());
		//ServerUserHandle suh = new ServerUserController();
		ServerUserHandle suh = injector.getInstance(ServerUserController.class);
		//ServerAdminHandle sah = injector.getInstance(ServerAdminController.class);
		UserManager um = injector.getInstance(UserManager.class);
		User u = um.getUserById(184);
		try {
			HauptmenueClient_gui window = new HauptmenueClient_gui(suh, u);
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		try {
			rm.unregisterClient(this);
			UnicastRemoteObject.unexportObject(this, true);
		} catch (NoSuchObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shell = new Shell();
		Rectangle screenSize = Display.getCurrent().getClientArea();
		shell.setSize(640, 510);
		shell.setMinimumSize(new Point(640, 480));
		shell.setLocation((screenSize.width-shell.getSize().x)/2, (screenSize.height-shell.getSize().y)/2);
	
		shell.setLayout(new FormLayout());
		
		
		shell.setText("Hauptmen\u00fc "+me.getUsername());
		
		final Display display = Display.getCurrent();
		Image icon = new Image(display, "icons/32/agt_web.png");
		shell.setImage(icon);

		final Composite left = new Composite(shell, SWT.NONE);
		left.setLayout(new FillLayout());
		final FormData fd_left = new FormData();
		fd_left.width = 79;
		fd_left.right = new FormAttachment(0, 90);
		fd_left.left = new FormAttachment(0, 10);
		left.setLayoutData(fd_left);

		/*
		 * final Table table_1 = new Table(left, SWT.BORDER);
		 * table_1.setLinesVisible(true); table_1.setHeaderVisible(true);
		 * table_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		 */

		// final Composite left = new Composite(shell, SWT.NONE);
		// left.setLayout(new FillLayout());
		gallery = new Gallery(left,SWT.BORDER);


		// Renderers
		NoGroupRenderer gr = new NoGroupRenderer();
		gr.setMinMargin(2);
		gr.setItemHeight(56);
		gr.setItemWidth(72);
		gr.setAutoMargin(true);
		gallery.setGroupRenderer(gr);

		DefaultGalleryItemRenderer ir = new DefaultGalleryItemRenderer();
		gallery.setItemRenderer(ir);

		GalleryItem group = new GalleryItem(gallery, SWT.NONE);
		group.setText("eLeitweg");
		group.setExpanded(true);
		
		final Composite right = new Composite(shell, SWT.NONE);
		final FormData fd_right = new FormData();
		fd_right.bottom = new FormAttachment(0, 355);
		fd_right.top = new FormAttachment(0, 10);
		fd_right.left = new FormAttachment(0, 298);
		fd_right.right = new FormAttachment(100, -14);
		right.setLayoutData(fd_right);
		right.setLayout(new FillLayout());

		table_1 = new Table(right, SWT.FULL_SELECTION | SWT.BORDER);
		table_1.setLinesVisible(true);
		table_1.setHeaderVisible(true);
		table_1.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent e) {
				
			}
			public void widgetSelected(SelectionEvent e) {
				selectedFile = (File) e.item.getData();

			}
		});

		final TableColumn DateienColumnTableColumn_1 = new TableColumn(table_1, SWT.NONE);
		DateienColumnTableColumn_1.setWidth(244);
		DateienColumnTableColumn_1.setText("Dateien");

		final TableColumn GroesseColumnTableColumn = new TableColumn(table_1, SWT.NONE);
		GroesseColumnTableColumn.setWidth(121);
		GroesseColumnTableColumn.setText("Gr\u00F6\u00DFe");

		final TableColumn TypColumnTableColumn = new TableColumn(table_1, SWT.NONE);
		TypColumnTableColumn.setWidth(157);
		TypColumnTableColumn.setText("Typ");

		final TableColumn geaendertAmColumnTableColumn = new TableColumn(table_1, SWT.NONE);
		geaendertAmColumnTableColumn.setWidth(185);
		geaendertAmColumnTableColumn.setText("Version");

		Composite middle;
		middle = new Composite(shell, SWT.NONE);
		fd_left.bottom = new FormAttachment(middle, 0, SWT.BOTTOM);
		fd_left.top = new FormAttachment(middle, 0, SWT.TOP);
		middle.setLayout(new FillLayout());
		final FormData fd_middle = new FormData();
		fd_middle.bottom = new FormAttachment(right, 0, SWT.BOTTOM);
		fd_middle.right = new FormAttachment(right, -23, SWT.LEFT);
		fd_middle.top = new FormAttachment(0, 10);
		fd_middle.left = new FormAttachment(left, 15, SWT.DEFAULT);
		middle.setLayoutData(fd_middle);

		table = new Table(middle, SWT.BORDER);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		
		table.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent e) {
				
			}
			public void widgetSelected(SelectionEvent e) {
				beschreibungDerInstanzText.setEnabled(true);
				if(isAcceptedSel()) {
					selectedIncomming = null;
					selectedStartable = null;
					selectedAccepted = (Run) e.item.getData();
					e.item.notifyListeners(SWT.SELECTED, new Event());
					if(selectedAccepted.getDesc() != null)
						beschreibungDerInstanzText.setText(selectedAccepted.getDesc());
					if(!(selectedAccepted.getNode().getId() == selectedAccepted.getWf().getStartnode().getId())) {
						beschreibungDerInstanzText.setEnabled(false);
					}
					
				} else if(isIncomingSel()) {
					selectedAccepted = null;
					selectedStartable = null;
					selectedIncomming = (Run) e.item.getData();
					e.item.notifyListeners(SWT.SELECTED, new Event());	
				} else if(isStartableSel()) {
					selectedIncomming = null;
					selectedAccepted = null;
					selectedStartable = (Workflow) e.item.getData();
					e.item.notifyListeners(SWT.SELECTED, new Event());	
				}

			}
		});

		final TableColumn newColumnTableColumn = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn.setWidth(128);
		newColumnTableColumn.setText("Auftr\u00E4ge");

		//final DragSource tableDragSource = new DragSource(table, DND.DROP_NONE);

		Composite leftButton;
		leftButton = new Composite(shell, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		leftButton.setLayout(gridLayout);
		final FormData fd_leftButton = new FormData();
		fd_leftButton.bottom = new FormAttachment(0, 410);
		fd_leftButton.right = new FormAttachment(middle, 0, SWT.RIGHT);
		fd_leftButton.left = new FormAttachment(left, 15, SWT.DEFAULT);
		fd_leftButton.top = new FormAttachment(middle, 20, SWT.DEFAULT);
		leftButton.setLayoutData(fd_leftButton);
		
		final Composite rightButton = new Composite(shell, SWT.NONE);
		final Button button_2 = new Button(rightButton, SWT.NONE);
		final Button button_3 = new Button(rightButton, SWT.NONE);
		final Button button_4 = new Button(rightButton, SWT.NONE);

		zuruecklegen = new Button(leftButton, SWT.NONE);
		zuruecklegen.addMouseListener(new MouseAdapter() {
			public void mouseUp(final MouseEvent e) {
				selectedIncomming = (Run)table.getSelection()[0].getData();
				Thread zuruecklegenThread = new Thread(new Runnable () {
					public void run() {
						try {
							rm.unacceptRun(selectedIncomming);
						} catch (RemoteException e1) {
							showError("Cannot reach server.", e1);
						}
					}
				});
				zuruecklegenThread.start();
				loadAccepted();
				table_1.removeAll();
				update();
			}
		});
		zuruecklegen.setText("Zuruecklegen");
		zuruecklegen.setVisible(false);
		akzeptierenButton = new Button(leftButton, SWT.NONE);
		akzeptierenButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(final MouseEvent e) {
				if(isIncomingSel() && selectedIncomming!=null) {
					//Here you are in the incoming view
					try {
						File eleitwegDir = FileHandler.prepareDir(me);
						int accId = selectedIncomming.getId();
						Thread acceptThread  = new Thread(new Runnable() {
							public void run() {
								try {
									rm.acceptRun(selectedIncomming, me);
								} catch (InconsistentDataException ide) {
									showError("A problem occured on server.", ide);
								} catch (RemoteException e1) {
									showError("Cannot reach server.", e1);
								}
							}
						});
						acceptThread.start();
						File runDir = FileHandler.getRunDir(eleitwegDir, selectedIncomming.getId());
						java.util.List<Document> docs = rm.getDocuments(selectedIncomming);
						for(Document d : docs) {
							File docFile = new File(runDir, d.getName());
							FileByteConverter.writeData(d.getBinary(), docFile);
						}
						gallery.setSelection(new GalleryItem[] { acceptedItem });
						button_2.setVisible(true);
						button_3.setVisible(true);
						button_4.setVisible(true);
						loadAccepted();
						for(int i=0;  i<table.getItemCount(); i++) {
							if(((Run) table.getItem(i).getData()).getId() == accId) {
								table.select(i);
								table.getItem(i).notifyListeners(SWT.SELECTED, new Event());
							}
						}
						table_1.removeAll();
						update();
					} catch (RemoteException e1) {
						showError("Cannot get document data.", e1);
					} catch (IOException e1) {
						showError("Cannot write to file.", e1);
					} 
					
				} else if(isAcceptedSel() && selectedAccepted != null) {
					//If your in accepted view then "weiterleiten"
					try {
						rm.uploadDocuments(selectedAccepted,documents);
					} catch(RemoteException r) { r.printStackTrace(); }
					documents = new ArrayList<Document>();
					table_1.removeAll();
					selectedAccepted.setDesc(beschreibungDerInstanzText.getText());
					beschreibungDerInstanzText.setText("");
					Weiterschicken ws = new Weiterschicken(shell, selectedAccepted, rm);
					ws.open();
					selectedAccepted = null;
					update();
				} else if(isStartableSel() && selectedStartable != null) {
					//If start is selected try to start a new workflow
					try {
						Run r = rm.createRun(selectedStartable, me, beschreibungDerInstanzText.getText());
						int accId = r.getId();
						log.debug("Started run " + r.getName() + " with user " + r.getUser().getUsername());
						gallery.setSelection(new GalleryItem[] { acceptedItem });
						button_2.setVisible(true);
						button_3.setVisible(true);
						button_4.setVisible(true);
						loadAccepted();
						for(int i=0;  i<table.getItemCount(); i++) {
							if(((Run) table.getItem(i).getData()).getId() == accId) {
								table.select(i);
								table.getItem(i).notifyListeners(SWT.SELECTED, new Event());
							}
						}
						update();
					} catch (RemoteException e1) {
						showError("Cannot reach server.", e1);
					}
					update();
				}
			}
		});
		akzeptierenButton.setVisible(false);
		final GridData gd_akzeptierenButton = new GridData(SWT.RIGHT,
				SWT.CENTER, true, false);
		gd_akzeptierenButton.widthHint = 80;
		akzeptierenButton.setLayoutData(gd_akzeptierenButton);
		akzeptierenButton.setText("&Akzeptieren");

		final GridLayout gridLayout_1 = new GridLayout();
		gridLayout_1.numColumns = 3;
		rightButton.setLayout(gridLayout_1);
		final FormData fd_rightButton = new FormData();
		fd_rightButton.bottom = new FormAttachment(0, 410);
		fd_rightButton.right = new FormAttachment(0, 626);
		fd_rightButton.left = new FormAttachment(right, 0, SWT.LEFT);
		fd_rightButton.top = new FormAttachment(leftButton, 0, SWT.TOP);
		rightButton.setLayoutData(fd_rightButton);

		final GridData gd_button_2 = new GridData(SWT.RIGHT, SWT.CENTER, true,
				false);
		gd_button_2.widthHint = 80;
		button_2.setLayoutData(gd_button_2);
		button_2.setText("&\u00D6ffnen");
		button_2.setVisible(false);
		button_2.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent m) {
				if(selectedFile != null) {
					try {
						log.info("Opening file: " + selectedFile.getAbsolutePath());
						Desktop.getDesktop().edit(selectedFile);
					} catch (Exception e) {
						try {
							log.warn("Cannot get default editor for " + selectedFile.getAbsolutePath() + ". Let's try something else.");
							Desktop.getDesktop().open(selectedFile);
						} catch (IOException e1) {
							showError("Die Datei " + selectedFile.getName() + " kann nicht ge\u00F6ffnet werden. " + e.getMessage(), e1);
						}
						
					}
				}
			}
		});

		button_3.setLayoutData(new GridData(80, SWT.DEFAULT));
		button_3.setText("&Hinzuf\u00FCgen");
		button_3.setVisible(false);
		button_3.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent m) {
				if(isAcceptedSel() && selectedAccepted != null) {
					FileDialog fd = new FileDialog(shell, SWT.OPEN | SWT.MULTI);
					String path = fd.open();
					if(path == null) {
						//user has clicked cancel
						return;
					}
					File source = new File(path);
					try {
						File dest = new File(FileHandler.getRunDir(FileHandler.prepareDir(me), selectedAccepted.getId()), source.getName());
						FileHandler.copy(source, dest);
						
						documents.add(new Document(0, dest.getName(), 1, FileByteConverter.fileToByte(dest), selectedAccepted));
						
					} catch (IOException e) {
						showError("Fehler beim Laden der Datei " + source.getAbsolutePath(), e);
					}

					update();
				}
			}
		});

		final GridData gd_button_4 = new GridData(SWT.RIGHT, SWT.CENTER, false,
				false);
		gd_button_4.widthHint = 80;
		button_4.setLayoutData(gd_button_4);
		button_4.setText("&L\u00F6schen");
		button_4.setVisible(false);
		button_4.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent m) {
				if(isAcceptedSel() && selectedAccepted != null && selectedFile != null) {
					MessageBox reallyDelete = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
					reallyDelete.setMessage("Wollen Sie wirklich " + selectedFile.getName() + " l\u00F6schen?");
					if(reallyDelete.open() == SWT.YES) {
						if(!selectedFile.delete()) {
							showError("Fehler beim L\u00F6schen von " + selectedFile.getName(), new Exception());
						}
						update();
					}
				}
			}
		});
		
		Image startableImage = new Image(display, "icons/32/cnrgrey.png");
		startableItem = new GalleryItem(group, SWT.NONE);
		startableItem.setText("Starten");
		startableItem.setImage(startableImage);
		startableItem.addListener(SWT.MouseUp, new Listener() {
			public void handleEvent(Event e) {
				button_2.setVisible(false);
				button_3.setVisible(false);
				button_4.setVisible(false);
				loadStartable();
			}
		});
		
		Image incomingImage = new Image(display, "icons/32/cnr-pending.png");
		incomingItem = new GalleryItem(group, SWT.NONE);
		incomingItem.setText("Eingehend");
		incomingItem.setImage(incomingImage);
		incomingItem.addListener(SWT.MouseUp, new Listener() {

			public void handleEvent(Event e) {
				button_2.setVisible(false);
				button_3.setVisible(false);
				button_4.setVisible(false);
				loadIncomming();
			}
		});
		
		Image acceptedImage = new Image(display, "icons/32/All software is current.png");
		acceptedItem = new GalleryItem(group, SWT.NONE);
		acceptedItem.setText("Akzeptiert");
		acceptedItem.setImage(acceptedImage);
		acceptedItem.addListener(SWT.MouseUp, new Listener() {

			public void handleEvent(Event e) {
				button_2.setVisible(true);
				button_3.setVisible(true);
				button_4.setVisible(true);
				loadAccepted();
			}
		});
				
		
		gallery.addListener(SWT.MouseUp, new Listener() {
			public void handleEvent(Event e) {
				if(isAcceptedSel()) {
					acceptedItem.notifyListeners(SWT.MouseUp, e);
				}
				if(isIncomingSel()) {
					incomingItem.notifyListeners(SWT.MouseUp, e);
				}
				if(isStartableSel()) {
					startableItem.notifyListeners(SWT.MouseUp, e);
				}
			}
		});

		final Menu menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);

		final MenuItem dateiMenuItem = new MenuItem(menu, SWT.CASCADE);
		dateiMenuItem.setText("Datei");

		final Menu menu_1 = new Menu(dateiMenuItem);
		dateiMenuItem.setMenu(menu_1);

		final MenuItem logoutMenuItem = new MenuItem(menu_1, SWT.NONE);
		logoutMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				shell.close();
				Login_gui window = new Login_gui();
				window.open();
			}
		});
		logoutMenuItem.setText("Logout");

		final MenuItem beendenMenuItem = new MenuItem(menu_1, SWT.NONE);
		beendenMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				shell.close();
				System.exit(0);
			}
		});
		beendenMenuItem.setText("Beenden");

		final MenuItem hilfeMenuItem = new MenuItem(menu, SWT.CASCADE);
		hilfeMenuItem.setText("Hilfe");

		final Menu menu_2 = new Menu(hilfeMenuItem);
		hilfeMenuItem.setMenu(menu_2);

		final MenuItem benutzerhandbuchMenuItem = new MenuItem(menu_2, SWT.NONE);
		benutzerhandbuchMenuItem.setText("Benutzerhandbuch");

		final MenuItem installationsleitfadenMenuItem = new MenuItem(menu_2, SWT.NONE);
		installationsleitfadenMenuItem.setText("Installationsleitfaden");

		final ExpandBar expandBar = new ExpandBar(shell, SWT.NONE);

		expandBar.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
		final FormData fd_expandBar = new FormData();
		fd_expandBar.bottom = new FormAttachment(100, -11);
		fd_expandBar.right = new FormAttachment(100, -5);
		fd_expandBar.top = new FormAttachment(leftButton, 5, SWT.BOTTOM);
		fd_expandBar.left = new FormAttachment(left, 0, SWT.LEFT);
		expandBar.setLayoutData(fd_expandBar);

		final ExpandItem newItemExpandItem = new ExpandItem(expandBar, SWT.NONE);
		newItemExpandItem.setHeight(50);
		newItemExpandItem.setText("Beschreibung der Instanz");
		

		final Composite composite = new Composite(expandBar, SWT.NONE);
		composite.setLayout(new FillLayout());
		newItemExpandItem.setControl(composite);

		beschreibungDerInstanzText = new Text(composite, SWT.WRAP | SWT.BORDER);
		beschreibungDerInstanzText.setTextLimit(400);
		waitCursor = new Cursor(Display.getCurrent(), SWT.CURSOR_WAIT);
		normCursor = new Cursor(Display.getCurrent(), SWT.CURSOR_ARROW);
		
		expandBar.addExpandListener(new ExpandAdapter() {
			public void itemCollapsed(final ExpandEvent e) {
				shell.setSize(shell.getSize().x, shell.getSize().y - expandBar.getSize().y + 25);
			}
			public void itemExpanded(final ExpandEvent e) {
				shell.setSize(shell.getSize().x, shell.getSize().y + newItemExpandItem.getHeight());
			}
		});
		//
	}
	
	/**
	 * This methode should be called be the server to refresh the tabs of the clients.
	 * It is called when anything on the server has changed.
	 */
	public void update() {
		log.debug("CLIENT UPDATE REQUEST!");
		display.syncExec(new Runnable() {
			public void run() {
				if (isAcceptedSel()) {
					loadAccepted();
				}
				if (isIncomingSel()) {
					loadIncomming();
				}
				if (isStartableSel()) {
					loadStartable();
				}
			}
		});
	}
	
	public void loadAccepted() {
		log.info("Loading accepted");
		shell.setCursor(waitCursor);
		table.removeAll();
		akzeptierenButton.setVisible(true);
		akzeptierenButton.setText("Weiterschicken");
		zuruecklegen.setVisible(true);
		try {
			java.util.List<Run> runs = rm.getMyRuns(me);
			log.info("This user has " + runs.size() + " accepted jobs.");
			for(Run r : runs) {
				TableItem ti = new TableItem(table, SWT.NONE);
				ti.setText(0, r.getName());
				ti.setData(r);
				ti.addListener(SWT.SELECTED, new AcceptedRunItemListener(r));
				ti.addListener(SWT.SELECTED, new RunItemDescListener(r));
			}
			if(selectedAccepted != null) {
				loadFilesTable(selectedAccepted);
			}
		} catch (RemoteException e1) {
			showError("Cannot reach server!", e1);
		}
		selectedIncomming = null;
		selectedFile = null;
		selectedStartable = null;
		beschreibungDerInstanzText.setText("");
		shell.setCursor(normCursor);
	}
	
	public void loadStartable() {
		log.info("Loading startable");
		shell.setCursor(waitCursor);
		table.removeAll();
		akzeptierenButton.setVisible(true);
		zuruecklegen.setVisible(false);
		akzeptierenButton.setText("Starten");
		try {
			java.util.List<Workflow> wfs = rm.getStartableWF(me);
			log.info("This user has " + wfs.size() + " startable jobs.");
			for(Workflow wf : wfs) {
				TableItem ti = new TableItem(table, SWT.NONE);
				ti.setText(0, wf.getName());
				ti.setData(wf);
			}

		} catch (RemoteException e1) {
			showError("Cannot reach server!", e1);
		}
		table_1.removeAll();
		selectedIncomming = null;
		selectedFile = null;
		selectedAccepted = null;
		beschreibungDerInstanzText.setText("");
		shell.setCursor(normCursor);
	}
	
	public void loadIncomming() {
		log.info("Loading incomming");
		shell.setCursor(waitCursor);
		table.removeAll();
		akzeptierenButton.setVisible(true);
		zuruecklegen.setVisible(false);
		akzeptierenButton.setText("Akzeptieren");
		try {
			java.util.List<Run> runs = rm.getAcceptableRuns(me);
			for(Run r : runs) {
				TableItem ti = new TableItem(table, SWT.NONE);
				ti.setText(0, r.getName());
				ti.setData(r);
				ti.addListener(SWT.SELECTED, new RunItemDescListener(r));
			}
		} catch (RemoteException e1) {
			showError("Cannot reach server!", e1);
		}
		table_1.removeAll();
		selectedFile = null;
		selectedAccepted = null;
		selectedStartable = null;
		beschreibungDerInstanzText.setText("");
		shell.setCursor(normCursor);
	}
	
	private class AcceptedRunItemListener implements Listener {
		private Run run;
		
		protected AcceptedRunItemListener(Run r) {
			this.run = r;
		}
		
		public void handleEvent(Event e) {
			loadFilesTable(run);
		}
	}
	
	private class RunItemDescListener implements Listener {
		private Run run;
		
		protected RunItemDescListener(Run r) {
			this.run = r;
		}
		
		public void handleEvent(Event e) {
			beschreibungDerInstanzText.setText("");
			if(run.getDesc()!=null) beschreibungDerInstanzText.setText(run.getDesc());
		}
	}
	
//	private class WorkflowItemDescListener implements Listener {
//		private Workflow workflow;
//		
//		protected WorkflowItemDescListener(Workflow workflow) {
//			this.workflow = workflow;
//		}
//		
//		public void handleEvent(Event e) {
//			beschreibungDerInstanzText.setText("");
//			if(workflow.getDesc()!=null) beschreibungDerInstanzText.setText(workflow.getDesc());
//		}
//	}
	
	private void loadFilesTable(Run run) {
		table_1.removeAll();
		File runDir = FileHandler.getRunDir(FileHandler.prepareDir(me), run.getId());
		for(File f : runDir.listFiles()) {
			TableItem ti = new TableItem(table_1, SWT.NONE);
			ti.setText(new String[] {f.getName(), Long.toString(f.length()/1000) + "KB", new MimetypesFileTypeMap().getContentType(f), ""});
			ti.setData(f);
		}
	}
	
	public void ping() {
		//pong!
	}

}
